package app.modules.cloudpivot.controller;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.UserFacade;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.web.api.controller.runtime.SystemPluginRuntimeController;
import com.authine.cloudpivot.web.api.handler.CustomizedOrigin;
import com.authine.cloudpivot.web.api.view.ResponseResult;

/**
 * 插件执行接口
 *
 * @author LiuGangQiang Create in 2025/07/02
 */
@RestController
@RequestMapping("/api/runtime/plugin")
@CustomizedOrigin(level = 1)
public class CustomPluginRuntimeController extends SystemPluginRuntimeController {
    private static final Logger LOG = LoggerFactory.getLogger(CustomPluginRuntimeController.class);
    @Value("${expand.file.preview.url:https://cloudpivot.lfans.cn:28009}")
    private String previewUrl;
    @Resource
    private UserFacade userFacade;

    @PostMapping("/{pluginPath}")
    public ResponseResult<JSONObject> executePlugin(@PathVariable String pluginPath, @RequestBody JSONObject pluginJson) {
        /* 只处理附件预览 */
        if ("documentProcess".equals(pluginPath)) {
            JSONObject config = new JSONObject();
            /* 这里可以自己定义预览地址 */
            String downloadUrl = pluginJson.getJSONObject("fileInfo").getString("filePath");
            String fileName = pluginJson.getJSONObject("fileInfo").getString("fileName");
            /* KKVIEW 预览word有问题这里特殊处理一下 */
            if (fileName.toLowerCase().endsWith(".doc") || fileName.toLowerCase().endsWith(".docx") || fileName.toLowerCase().endsWith(".docm")) {
                return super.executePlugin(pluginPath, pluginJson);
            }
            StringBuffer viewUrl = new StringBuffer().append(downloadUrl).append("&fullfilename=").append(fileName);
            /* 处理水印 */
            UserModel user = userFacade.get(getUserId());
            StringBuffer watermark = new StringBuffer();
            watermark.append(user.getName())
                    .append("-")
                    .append(user.getUserId())
                    .append("(")
                    .append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                    .append(")");
            /* 生成预览链接 kkview url需要用URL编码原文的BASE64字符串 水印需要使用URL编码 */
            StringBuffer documentUrl = new StringBuffer().append(previewUrl)
                    .append("/onlinePreview?url=")
                    .append(urlencode(base64encode(viewUrl.toString().trim())))
                    .append("&watermarkTxt=")
                    .append(urlencode(watermark.toString().trim()));
            config.put("documentUrl", documentUrl);
            config.put("channelType", "kkview");
            LOG.info("===>>KKVIEW预览信息：{}", documentUrl);
            return getOkResponseResult(config, "操作成功！");
        } else {
            /* 其他情况走默认 */
            return super.executePlugin(pluginPath, pluginJson);
        }
    }

    /**
     * URL转码
     *
     * @author LiuGangQiang Create in 2025/07/05
     * @param original 原文
     * @return {@link String}
     */
    private String urlencode(String original) {
        try {
            return URLEncoder.encode(original, StandardCharsets.UTF_8.toString());
        } catch (Exception e) {
            LOG.error("===>>URL转码错误 错误消息：{}", e.getMessage());
            throw new RuntimeException("预览URL转码错误", e);
        }
    }

    /**
     * Base64转码
     *
     * @author LiuGangQiang Create in 2025/07/05
     * @param original 原文
     * @return {@link String}
     */
    private String base64encode(String original) {
        try {
            return Base64.getEncoder().encodeToString(original.getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            LOG.error("===>>BASE64转码错误 错误消息：{}", e.getMessage());
            throw new RuntimeException("预览BASE64转码错误", e);
        }
    }
}
